package jp.dodododo.reloadable.net;

import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class URLClassLoaderEx extends URLClassLoader {

	private URL[] urls;

	public URLClassLoaderEx(URL[] urls, ClassLoader classloader, URLStreamHandlerFactory urlstreamhandlerfactory) {
		super(urls, classloader, urlstreamhandlerfactory);
		this.urls = urls;
	}

	public URLClassLoaderEx(URL[] urls, ClassLoader classloader) {
		super(urls, classloader);
		this.urls = urls;
	}

	public URLClassLoaderEx(URL[] urls) {
		super(urls);
		this.urls = urls;
	}

	@Override
	public URL[] getURLs() {
		List<URL> list = new ArrayList<URL>();
		addURLs(list, this);
		return list.toArray(new URL[list.size()]);
	}

	private void addURLs(List<URL> list, ClassLoader loader) {
		if (loader == null) {
			return;
		}
		URL[] url = null;
		if (loader instanceof URLClassLoaderEx) {
			url = ((URLClassLoaderEx) loader).urls;
		} else if (loader instanceof URLClassLoader) {
			url = ((URLClassLoader) loader).getURLs();
		}
		if (url != null && 0 < url.length) {
			list.addAll(Arrays.asList(url));
		}
		addURLs(list, loader.getParent());
	}
}
